package ita.class1.group2.supermarket.administrator.service;

import ita.class1.group2.supermarket.administrator.dao.AdFormDaoImpl;
import ita.class1.group2.supermarket.administrator.pojo.AdForm;
import ita.class1.group2.supermarket.administrator.pojo.AdStore;
import ita.class1.group2.supermarket.administrator.pojo.Store;
import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.pojo.Page;

import java.sql.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class AdFormService {

    @Autowired
    private AdFormDaoImpl adFromDao;
    @Autowired
    private StoreService storeService;

    public void saveAddForm(AdForm adForm) {
        AdForm af = adFromDao.save(adForm);
    }

    public List<AdForm> getAllAd() {
        List<AdForm> all = adFromDao.findAll();
        return all;
    }

    public void updateAd(String id, String uid) {
        AdForm adForm = adFromDao.find(id);
        adForm.setConsumeTime(new Date(System.currentTimeMillis()));
        adForm.setConsumeUId(uid);
        Map<String, Object> map = null;
        if(adForm.getUpdatetime() != 0 && adForm.getUpdatetime()!= null){
            map = new HashMap<String, Object>();
            map.put("update_time", adForm.getUpdatetime());
        }
        adFromDao.updateByCon(adForm, map);
    }

    public List<AdStore> getConfirmAd() {
        List<AdForm> adForms = adFromDao.findByConWithSort(null, false, "CONSUME_TIME", 3);
        List<AdStore> adStores = new LinkedList<AdStore>();
        for (AdForm ad : adForms) {
            Store store = storeService.getStoreById(ad.getsId());
            adStores.add(new AdStore(ad, store, null));
        }
        return adStores;
    }

    public AdStore getConfirmAdById(String id) {

        AdForm adForm = adFromDao.find(id);
        AdStore adStore = new AdStore();
        Store store = storeService.getStoreById(adForm.getsId());
        adStore.setAdForm(adForm);
        adStore.setStore(store);
        return adStore;
    }

    public Page<AdForm> getAdByPage(Integer page, Integer pageCount) {
        List<AdForm> adForms = adFromDao.superFind(null, null, null, page, pageCount);
        int count = adFromDao.findCount(null);
        Page<AdForm> pages = new Page<AdForm>(page,pageCount,adForms,count);
        return pages;
    }

    public AdForm getAdStatusBySid(String id) {
        Map<String,String> map = new HashMap<String,String>();
        map.put("SID",id);
        List<AdForm> adForms = adFromDao.findByCondition(map);
        if(adForms != null && adForms.size() > 0){
            return adForms.get(0);
        }
        return null;
    }
}
